Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

174
Visualizações
"wheel" event is being fired infinitly and crashing my website
import React, { useEffect, useState } from "react";
import "./Skill.css";
import { Fade } from "react-reveal";
function Skill({ name, color }) {
  const [style, setStyle] = useState({ borderBottom: `4px solid ${color}` });
  
  window.addEventListener("wheel", () => {
    let scroll = window.scrollY;
    console.log(scroll);
    if (scroll >= 1300) {
      setStyle({
        animation: "load 2s ease-out",
        display: "block",
        borderBottom: `4px solid ${color}`,
      });
    }
  });
  return (
    <>
      <div className="skill">
        <Fade bottom>
          <div className="Skill__logo">
            <img
              className="logo__img"
              src="./images/html-5-logo-svgrepo-com.svg"
              alt=""
            />
          </div>
          <div className="skills__about">
            <div className="skillitem">
              <div className="skill__set">
                <div className="skill__Name" style={{ color: color }}>
                  {name}
                </div>
              </div>
              <div style={style} className="loading__skill"></div>
            </div>
          </div>
        </Fade>
      </div>
    </>
  );
}

export default Skill;

Here is my code and I dunno for some reason the wheel event is firing infinitely and crashing my application kindly if somebody can tell me what is the issue

I dunno for some reason the wheel event is firing infinitely and crashing my application kindly if somebody can tell me what is the issue

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

When setStyle inside the wheel event listener callback is called - the Skill component is refreshed which then invokes window.addEventListener("wheel", () => { again; adding another callback to the window and because wheel was what was called initially it is called again, hence repeating this loop infinitely.

This can be fixed easily by adding the logic that is only meant to be getting triggered by the first render inside a useEffect hook which has the second parameter as [], like so:

useEffect(() => {
  window.addEventListener("wheel", () => {
    let scroll = window.scrollY;
    console.log(scroll);
    if (scroll >= 1300) {
      setStyle({
        animation: "load 2s ease-out",
        display: "block",
        borderBottom: `4px solid ${color}`,
      });
    }
  });
}, []);

The above however is a quick workaround to your solution. window based properties should realistically be controlled in the parent-most component of the application to avoid global variable pollution and maintainability the event listeners that are exerted on the application in a cohesive manner.

about 4 years ago · Juan Pablo Isaza Relatório

0

The reason may be because when you scroll, the wheel event is fired many times. You can try to apply a debouncing script.

// ...more code
function debounce(func, timeout = 300){
  let timer;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => { func.apply(this, args); }, timeout);
  };
}
 window.addEventListener("wheel", debounce(() => {
    let scroll = window.scrollY;
    console.log(scroll);
    if (scroll >= 1300) {
      setStyle({
        animation: "load 2s ease-out",
        display: "block",
        borderBottom: `4px solid ${color}`,
      });
    }
  }));
// ...more code

The example limits it to firing every 300 milliseconds, or every 0.3 of a second.

about 4 years ago · Juan Pablo Isaza Relatório

0

Remember, every time you set state or change a prop, a render cycle is incurred. And, in your component, at every render cycle you are setting a listener on the scroll event that you never unset. Furthermore, one of the actions in your listener handler is to set state, which will invoke another render, which creates yet another listener, to invoke another render-- you can see where this is approaching an infinite loop-like situation.

What you should do is use the useState hook, to set your handler on the initial render only, and then return a function that unsets the listener on the unmount of the component:

// define handleWheel outside your function, or with `useCallback` to set a persistent reference
const handleWheel = () => {
  let scroll = window.scrollY;
  console.log(scroll);
  if (scroll >= 1300) {
    setStyle({
      animation: "load 2s ease-out",
      display: "block",
      borderBottom: `4px solid ${color}`,
    });
  }
}


// later, in your component:
useState(() => {
  window.addEventListener("wheel", handleWheel);
  return () => window.removeEventListener("wheel", handleWheel); // to be called at unmount of component
}, []); // empty array ensures it will be called only at first render
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda